package edu.neumont.MillerK.AndroidServlets;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;

import javax.annotation.Resource;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.UserTransaction;

import edu.neumont.MillerK.POJOs.Security;
import edu.neumont.MillerK.Web.DBQueries.DBQueries;
import edu.neumont.MillerK.Web.Entities.Location;
import edu.neumont.MillerK.Web.Entities.User;

/**
 * Servlet implementation class AndroidLocationServlet
 */
@WebServlet("/AndroidLocations")
public class AndroidLocationServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	@Resource
	UserTransaction utx;
	
	@PersistenceUnit
	EntityManagerFactory emf;

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		DBQueries dbQueries = new DBQueries(emf, utx);
		Security security = new Security();
		String emailUsername = request.getParameter("emailUsername");
		String password = request.getParameter("password");
		System.out.println("Latitude: " + request.getParameter("latitude") + " Longitude: " + request.getParameter("longitude")
				+ " Altitude: " + request.getParameter("altitude") + " Date: " + request.getParameter("time"));
		Location newLocation = new Location(request.getParameter("latitude"), request.getParameter("longitude"),
				request.getParameter("altitude"), request.getParameter("time"));
		User user = dbQueries.getUser(emailUsername);
		newLocation.setOwner(user);
		if(user != null){
			try {
				if(user.getPassword().equals(security.SHAHash(password + user.getSalt()))){
					dbQueries.updateUserLocations(user, newLocation);
				}
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			}
		}
	}

}
